package com.fsnbigdata.config;

import com.fsnbigdata.domain.security.User;
import com.fsnbigdata.service.api.LogService;
import com.fsnbigdata.service.api.UserService;
import com.fsnbigdata.util.Email;
import com.fsnbigdata.util.PublicStaticData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * Created by zhongcheng on 22/12/2017.
 */
@Configuration
@EnableCaching
@EnableScheduling
public class CacheConfiguration {

    private static final Log logger = LogFactory.getLog(CacheConfiguration.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @CacheEvict(value = "statistic_count", allEntries = true )
    @Scheduled(fixedDelay = 5 * 60 * 1000 ,  initialDelay = 1000)
    public void statisticCountCacheEvict() {
        logger.debug("Flush Cache");
    }

    @CacheEvict(value = "creation_count", allEntries = true )
    @Scheduled(fixedDelay = 5 * 60 * 1000 ,  initialDelay = 1000)
    public void creationCountCacheEvict() {
        logger.debug("Flush Cache");
    }


    @Scheduled(cron ="0 0 9 ? * MON")
//    @Scheduled(cron ="*/10 * * * * ? ")
    public void sendEmailToAdmin(){
        Email email = new Email();
        User user = userService.findByUsername("admin");
        if(user==null){
            logger.debug("没有找到管理员！");
        }
        if(user.getEmail()==null){
            logger.debug("管理员没有绑定邮箱!");
        }
        //mysql数据库的时间戳精确到秒，java的时间戳精确到毫秒
        long time = new Date().getTime()/1000;
        //获取除开超级管理员的登录次数
        Long count = logService.getCount("login","admin",time- PublicStaticData.ADMIN_LOGIN_COUNT_TIME,time);
//        Long count = logService.getCount("login","admin",time-10,time);
        //如果次数小于规定次数
        if(count< PublicStaticData.ADMIN_LOGIN_COUNT){
            try {
//                email.sendMailToAdmin(user.getEmail(),"致尊敬的管理员","10秒内",1);
                email.sendMailToAdmin(user.getEmail(),PublicStaticData.EMAIL_SENDER, PublicStaticData.ADMIN_LOGIN_COUNT_TIME_DESCRIBE, PublicStaticData.ADMIN_LOGIN_COUNT);
                logger.debug("邮件发送成功！");
            }catch (Exception e){
                logger.debug("邮件发送失败，失败原因："+e.getMessage());
            }

            logger.debug(":Send Email To Admin!");
        }
    }
}
